import { makeAutoObservable, toJS } from "mobx";
import cloneDeep from "lodash.clonedeep";
import type { surveyType } from "@/types/index";
import storage from "@/utils/storage";

const info: { surveyData: surveyType[]; surveyId: string } = {
  surveyData: storage.getSession("SURVEYDATA") || [],
  surveyId: localStorage.getItem("SURVEYID") || ""
};

export const surveyStore = makeAutoObservable({
  surveyData: info.surveyData,
  surveyId: info.surveyId,
  /**获取调查*/
  surveySelected(id: string): surveyType {
    return cloneDeep(toJS(this.surveyData.filter(item => item.id === id)[0]));
  },
  /**新增调查*/
  surveyAdd(survey: surveyType) {
    console.log("survey", survey);
    this.surveyData.unshift(survey);
    storage.setSession("SURVEYDATA", this.surveyData);
  },
  /**调查修改*/
  surveyModify(survey: surveyType) {
    const index = this.surveyData.findIndex(item => {
      return item.id === survey.id;
    });
    this.surveyData[index] = survey;
    storage.setSession("SURVEYDATA", this.surveyData);
  },
  /**状态修改*/
  stateModify(id: string, state: boolean) {
    this.surveyData.forEach(item => {
      if (item.id == id) item.state = state;
    });
    storage.setSession("SURVEYDATA", this.surveyData);
  },
  /**调查删除*/
  surveyErasure(id: string) {
    this.surveyData = this.surveyData.filter(item => item.id !== id);
    storage.setSession("SURVEYDATA", this.surveyData);
  },
  // 修改调查id
  modifySurveyId(id: string) {
    this.surveyId = id;
    localStorage.setItem("SURVEYID", id);
  }
});
